const ffmpeg = require('fluent-ffmpeg');
const path = require('path');
const fs = require('fs-extra');

/**
 * 视频信息获取辅助类
 */
class VideoInfoHelper {
    constructor(downloadDir) {
        this.downloadDir = downloadDir;
    }

    /**
     * 根据文件名查找文件
     */
    async findFileByName(fileName) {
        const searchDirs = [
            this.downloadDir,
            path.join(this.downloadDir, 'processed'),
            path.join(__dirname, '..', 'outputs'),
            path.join(__dirname, '..', 'downloads')
        ];

        for (const dir of searchDirs) {
            if (await fs.pathExists(dir)) {
                const files = await this.getAllFiles(dir);
                const found = files.find(file => 
                    path.basename(file) === fileName || 
                    path.basename(file, path.extname(file)) === path.basename(fileName, path.extname(fileName))
                );
                if (found) {
                    return found;
                }
            }
        }

        // 如果是绝对路径且文件存在，直接返回
        if (path.isAbsolute(fileName) && await fs.pathExists(fileName)) {
            return fileName;
        }

        return null;
    }

    /**
     * 递归获取目录下所有文件
     */
    async getAllFiles(dir) {
        const files = [];
        
        try {
            const items = await fs.readdir(dir);
            
            for (const item of items) {
                const fullPath = path.join(dir, item);
                const stat = await fs.stat(fullPath);
                
                if (stat.isDirectory()) {
                    const subFiles = await this.getAllFiles(fullPath);
                    files.push(...subFiles);
                } else {
                    files.push(fullPath);
                }
            }
        } catch (error) {
            // 忽略无法访问的目录
        }
        
        return files;
    }

    /**
     * 获取视频信息
     * @param {string} inputFile - 输入视频文件
     * @returns {Promise<Object>} 视频信息 {duration, width, height, fps, orientation, bitrate, format, size}
     */
    async getVideoInfo(inputFile) {
        const resolvedPath = await this.findFileByName(inputFile);
        if (!resolvedPath) {
            throw new Error(`找不到视频文件: ${inputFile}`);
        }

        return new Promise((resolve, reject) => {
            ffmpeg.ffprobe(resolvedPath, (err, metadata) => {
                if (err) {
                    console.error('获取视频信息失败:', err);
                    reject(err);
                    return;
                }

                const videoStream = metadata.streams.find(stream => stream.codec_type === 'video');
                if (!videoStream) {
                    reject(new Error('未找到视频流'));
                    return;
                }

                // 计算视频方向
                let orientation = '横向';
                if (videoStream.width && videoStream.height) {
                    if (videoStream.height > videoStream.width) {
                        orientation = '竖向';
                    } else if (videoStream.height === videoStream.width) {
                        orientation = '方形';
                    }
                }

                // 计算比特率
                let bitrate = null;
                if (videoStream.bit_rate) {
                    bitrate = Math.round(parseInt(videoStream.bit_rate) / 1000); // 转换为 kbps
                } else if (metadata.format.bit_rate) {
                    bitrate = Math.round(parseInt(metadata.format.bit_rate) / 1000); // 转换为 kbps
                }

                const info = {
                    duration: metadata.format.duration,
                    width: videoStream.width,
                    height: videoStream.height,
                    fps: eval(videoStream.r_frame_rate) || 30,
                    orientation: orientation,
                    bitrate: bitrate,
                    format: metadata.format.format_name,
                    size: metadata.format.size
                };

                resolve(info);
            });
        });
    }
}

module.exports = VideoInfoHelper;